package com.fast.linkbeanadmin.security.impl;

import com.fast.linkbeanadmin.constants.CacheConstants;
import com.fast.linkbeanadmin.pojo.dto.SecurityUserDTO;
import com.fast.linkbeanadmin.pojo.response.ResultBean;
import com.fast.linkbeanadmin.utils.redis.RedisUtil;
import com.fast.linkbeanadmin.utils.response.ResponseUtil;
import org.springframework.cache.CacheManager;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ruan cai yuan
 * @version 1.0
 * @fileName com.fast.linkbeanadmin.security.handlerImpl.LogoutHandlerImpl
 * @description: TODO
 * @since 2024/7/21 下午5:58
 */
@Component
public class LogoutHandlerImpl implements LogoutHandler {
    @Resource
    private RedisUtil redisUtil;
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof SecurityUserDTO) {
            SecurityUserDTO dto = (SecurityUserDTO) principal;
            // 1. 清除当前登录用户redis中缓存
            redisUtil.delete(CacheConstants.LOGIN_USERNAME_KEY + dto.getUsername());
            // 清空security 上下文 filterChain,在SecurityContextPersistenceFilter中已清空
            // 2. 返回信息给前端
            ResultBean success = ResultBean.success("注销成功");
            ResponseUtil.responseData(response, success, MediaType.APPLICATION_JSON_VALUE);
        }

    }
}
